﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

namespace WebApplication1
{
    public partial class SchoolEditBySchoolAccount : System.Web.UI.Page
    {
        public string strJ
        {
            get;
            set;
        }
        public string strW
        {
            get;
            set;
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["UserInfo"] == null || ((Entity.UserInfo)Session["UserInfo"]).UserType != "School")
            {
                Response.Redirect("~/Search.aspx");
            }
            if (SQLHelper.getSchoolIdBySchoolAccountId(((Entity.UserInfo)Session["UserInfo"]).UserId) == -1)
            {
                Response.Write("<script>alert('尚未绑定学校，请联系管理员!');location.href='WelcomeSchoolAccount.aspx';</script>");
                return;
            }

            Session.Add("SchoolId", SQLHelper.getSchoolIdBySchoolAccountId(((Entity.UserInfo)Session["UserInfo"]).UserId));
            if (!IsPostBack)
            {
                //configrate treeview nodes
                tvTag.Nodes.Clear();
                TreeNode rootNode = new TreeNode();
                TreeNode childNode = new TreeNode();
                TreeNode leafNode = new TreeNode();
                DataTable dtRootTags = new DataTable();
                DataTable dtChildTags = new DataTable();
                DataTable dtLeafTags = new DataTable();

                SQLHelper.getRootTags(out dtRootTags);
                for (int ix = 0; ix < dtRootTags.Rows.Count; ix++)
                {
                    rootNode = new TreeNode(dtRootTags.Rows[ix]["TagName"].ToString(), dtRootTags.Rows[ix]["Id"].ToString());
                    rootNode.SelectAction = TreeNodeSelectAction.None;
                    tvTag.Nodes.Add(rootNode);
                    SQLHelper.getChildTagsByParentId(Convert.ToInt32(rootNode.Value), out dtChildTags);
                    for (int iy = 0; iy < dtChildTags.Rows.Count; iy++)
                    {
                        childNode = new TreeNode(dtChildTags.Rows[iy]["TagName"].ToString(), dtChildTags.Rows[iy]["Id"].ToString());
                        childNode.SelectAction = TreeNodeSelectAction.None;
                        tvTag.Nodes[ix].ChildNodes.Add(childNode);
                        SQLHelper.getChildTagsByParentId(Convert.ToInt32(childNode.Value), out dtLeafTags);
                        for (int iz = 0; iz < dtLeafTags.Rows.Count; iz++)
                        {
                            leafNode = new TreeNode(dtLeafTags.Rows[iz]["TagName"].ToString(), dtLeafTags.Rows[iz]["Id"].ToString());
                            leafNode.SelectAction = TreeNodeSelectAction.None;
                            tvTag.Nodes[ix].ChildNodes[iy].ChildNodes.Add(leafNode);
                        }
                    }

                }






                if (Session["SchoolId"] == null)
                {
                    strJ = "121";
                    strW = "31";
                }
                else
                {
                    int id = Convert.ToInt32(Session["SchoolId"]);
                    DataTable dtInfo = new DataTable();
                    SQLHelper.getSchoolInfoById(id, out dtInfo);
                    strJ = dtInfo.Rows[0]["Longitude"].ToString();
                    strW = dtInfo.Rows[0]["Latitude"].ToString();
                    tbxName.Text = dtInfo.Rows[0]["Name"].ToString();
                    tbxAddress.Text = dtInfo.Rows[0]["Address"].ToString();
                    tbxLongitude.Text = dtInfo.Rows[0]["Longitude"].ToString();
                    tbxLatitude.Text = dtInfo.Rows[0]["Latitude"].ToString();
                    ddlType.Text = dtInfo.Rows[0]["Type"].ToString();
                    tbxPhone.Text = dtInfo.Rows[0]["Phone"].ToString();
                    tbxBriefIntroduction.Text = dtInfo.Rows[0]["BriefInfo"].ToString();

                    //show checked treeview nodes
                    DataTable m_dt = new DataTable();
                    SQLHelper.getTagsBySchoolId(id, out m_dt);
                    for (int ix = 0; ix < m_dt.Rows.Count; ix++)
                    {
                        foreach (TreeNode m_rootNode in tvTag.Nodes)
                        {
                            if (m_dt.Rows[ix]["Id"].ToString() == m_rootNode.Value.ToString())
                            {
                                m_rootNode.Checked = true;
                                break;
                            }
                            foreach (TreeNode m_childNode in m_rootNode.ChildNodes)
                            {
                                if (m_dt.Rows[ix]["Id"].ToString() == m_childNode.Value.ToString())
                                {
                                    m_childNode.Checked = true;
                                    break;
                                }
                                foreach (TreeNode m_leafNode in m_childNode.ChildNodes)
                                {
                                    if (m_dt.Rows[ix]["Id"].ToString() == m_leafNode.Value.ToString())
                                    {
                                        m_leafNode.Checked = true;
                                        break;
                                    }
                                }
                            }
                        }
                    }





                }
            }
        }

        protected void btnOK_Click(object sender, EventArgs e)
        {
            if (tbxName.Text == "")
            {
                Response.Write("<script language = javascript>alert('请输入培训机构名称');</script>");
                return;
            }
            if (tbxAddress.Text == "")
            {
                Response.Write("<script language = javascript>alert('请输入培训机构地址');</script>");
                return;
            }
            if (tbxLatitude.Text == "" || tbxLongitude.Text == "")
            {
                Response.Write("<script language = javascript>alert('请输入培训机构坐标');</script>");
                return;
            }
            if (tbxBriefIntroduction.Text == "")
            {
                Response.Write("<script language = javascript>alert('请输入学校简介');</script>");
                return;
            }

            if (Session["SchoolId"] != null)
            {

                int id = Convert.ToInt32(Session["SchoolId"]);
                try
                {
                    int iresult = SQLHelper.UpdateSchoolById(id, tbxName.Text, tbxAddress.Text, float.Parse(tbxLongitude.Text), float.Parse(tbxLatitude.Text), ddlType.Text, tbxPhone.Text, tbxBriefIntroduction.Text);
                    SQLHelper.deleteTagBySchoolId(id);

                    foreach (TreeNode rootNode in tvTag.Nodes)
                    {
                        Entity.TreeViewHelper.navigateNodes(rootNode, id);
                    }
                    if (iresult == 1)
                    {
                        Session.Remove("SchoolId");
                        Response.Write("<script>alert('编辑成功!');location.href='WelcomeSchoolAccount.aspx';</script>");
                    }
                    else
                    {
                        Session.Remove("SchoolId");
                        Response.Write("<script>alert('编辑失败!');location.href='WelcomeSchoolAccount.aspx';</script>");
                    }
                }
                catch (Exception ex)
                {
                    Session.Remove("SchoolId");
                    Response.Write("<script>alert('" + ex.Message + "');location.href='WelcomeSchoolAccount.aspx';</script>");
                }





            }
            else
            {
            }

        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Session.Remove("SchoolId");
            Response.Redirect("WelcomeSchoolAccount.aspx");
        }

        protected void tvTag_TreeNodeCheckChanged(object sender, TreeNodeEventArgs e)
        {
            //Recursive change its children's checked states.
            RecursiveCheckCheckBox(e.Node, e.Node.Checked, true);

            //If current node is unchecked then check whether all its sibling are
            // unchecked, if so, unchecked its parent node.
            TreeNode current = e.Node;
            while (!current.Checked && current.Parent != null && !IsChildNodesChecked(current.Parent))
            {
                current.Parent.Checked = false;
                current = current.Parent;
            }

            //If current node is checked then recursive checked its ancestor nodes.
            if (e.Node.Checked)
            {
                RecursiveCheckCheckBox(e.Node, e.Node.Checked, false);
            }

        }
        private bool IsChildNodesChecked(TreeNode n)
        {
            bool result = false;
            if (n.ChildNodes.Count == 0)
            {
                result = n.Checked;
            }
            foreach (TreeNode t in n.ChildNodes)
            {
                if (result |= t.Checked)
                {
                    break;
                }
            }
            return result;
        }
        private void RecursiveCheckCheckBox(TreeNode n, bool isChecked, bool topDown)
        {
            if (topDown)
            {
                foreach (TreeNode l in n.ChildNodes)
                {
                    l.Checked = isChecked;
                    if (l.ChildNodes.Count != 0)
                    {
                        RecursiveCheckCheckBox(l, isChecked, topDown);
                    }
                }
            }
            else
            {
                n.Checked = isChecked;
                if (n.Parent != null)
                {
                    RecursiveCheckCheckBox(n.Parent, isChecked, false);
                }
            }
        }

        protected void tvTag_TreeNodeCheckChanged1(object sender, TreeNodeEventArgs e)
        {
            //Recursive change its children's checked states.
            RecursiveCheckCheckBox(e.Node, e.Node.Checked, true);

            //If current node is unchecked then check whether all its sibling are
            // unchecked, if so, unchecked its parent node.
            TreeNode current = e.Node;
            while (!current.Checked && current.Parent != null && !IsChildNodesChecked(current.Parent))
            {
                current.Parent.Checked = false;
                current = current.Parent;
            }

            //If current node is checked then recursive checked its ancestor nodes.
            if (e.Node.Checked)
            {
                RecursiveCheckCheckBox(e.Node, e.Node.Checked, false);
            }
        }
    }
}